package jmd.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class CommandServer
{

	String[] allTheIp =
	{"192.0.0.1" , "192.0.0.2" , "192.0.0.3"};
	// 返回菜单
	protected static final Object[] BACK =
	{"Q" , "Back to previous menu" , null};
	protected static final String UNDERLINE = "-----------------------------------------------------------------------------";

	// 二级菜单
	private static final Object[][] SEC_MENU =
	{
	// mnemonic, description, method
			{"1" , "Please choose one to disconect" , "chooseOneToDelete"} , BACK

	};

	/**
	 * Define all the variable
	 */
	protected BufferedReader _stdin;
	protected FormattingPrintWriter _stdout;
	protected String title = null;

	public static String DeleteIP = "";

	public CommandServer()
	{
		_stdin = new BufferedReader(new InputStreamReader(System.in));
		_stdout = new FormattingPrintWriter(System.out, true);
		title = "Command Client";
		_stdout.println("\n--- " + title + "  ---");
	}

	// 选择菜单选项，动态调用某个方法
	public void doMenu(Object[][] menu, boolean main)
	{
		this.doMenu(this.title, menu, main);
	}

	/**
	 * 菜单选项具体实现方法
	 * 
	 * @param pTitle
	 * @param menu
	 * @param main
	 */
	public void doMenu(String pTitle, Object[][] menu, boolean main)
	{

		synchronized (System.in)
		{
			Map actions = new HashMap();
			StringBuffer sb = new StringBuffer(menu.length);
			for (int i = 0; i < menu.length; i++)
			{
				Object mnemonic = menu[i][0];
				sb.append(mnemonic);
				Object action = menu[i][2];
				if (action instanceof String)
					action = findMethod((String) action);
				actions.put(mnemonic, action);
			}
			String choices = sb.toString();
			while (true)
			{// ///////////////////////////////////////////////////////////
				try
				{
					String mnemonic;
					_stdout.clearTabs();
					_stdout.println("\n---   " + pTitle + "   ---");
					_stdout.println("\nEnter choice:");
					for (int i = 0; i < menu.length; i++)
						_stdout.println(menu[i][0] + ") " + menu[i][1]);
					// Get the user's selection.
					mnemonic = getChoice(choices);
					// System.out.println("mnemonic="+mnemonic);
					for (int i = 0; i < menu.length; i++)
					{
						Object[] entry = menu[i];
						if (entry[0].equals(mnemonic))
						{
							Object action = actions.get(mnemonic);
							if (action == null)
							{
								return;
							} else if (action instanceof Method)
							{
								// System.out.println("selected,will do");
								// Cast required to suppress JDK1.5 varargs compiler warning.
								((Method) action).invoke(this, (Object[]) null);
							} else
							{
								doMenu((String) entry[1], (Object[][]) action, false);
							}
						}
					}
				} catch (Exception e)
				{
					Throwable t = e;
					if (e instanceof InvocationTargetException)
						t = ((InvocationTargetException) e).getTargetException();
					_stdout.println("\007*** Caught exception: " + t);
				}
			}// //////////////////////////////////////////////////////////////////////////
		}

	}

	/**
	 * through the name we can find the method
	 * 
	 * @param name
	 * @return
	 */
	private Method findMethod(String name)
	{
		Class cl = getClass();
		Method method = null;
		while (method == null)
		{
			try
			{
				method = cl.getDeclaredMethod(name, null);
			} catch (NoSuchMethodException e)
			{
				System.out.println("no method define");
				cl = cl.getSuperclass();
				if (cl == null)
				{
					e.printStackTrace();
					System.exit(1);
				}
				/*
				 * try { return cl.getDeclaredMethod("done", null); } catch
				 * (NoSuchMethodException ex) {ex.printStackTrace();}
				 */
			}
		}
		return method;
	}

	/**
	 * get the choice you select
	 * 
	 * @param choices
	 * @return
	 * @throws IOException
	 */
	protected String getChoice(String choices) throws IOException
	{
		while (true)
		{
			_stdout.print("> ");
			_stdout.flush();
			String line = _stdin.readLine().trim();
			if (line.length() == 1)
			{
				int choice = Character.toUpperCase(line.charAt(0));
				int index = choices.indexOf(choice);
				if (index != -1)
					return choices.substring(index, index + 1);
			}
			_stdout.println("\007*** Choice must be one of: " + choices);
		}
	}

	/**
	 * choose one ip to delete
	 * 
	 * @throws IOException
	 */
	public void chooseOneToDelete()
	{
		System.out.println("size is " + AyServer.clients.size());
		for (int i = 0; i < AyServer.clients.size(); i++)
		{

			System.out.println(i + 1 + "    " + AyServer.clients.get(i).getIp()
					+ "/n");
		}
		/**
		 * here we will list the client connected to the server
		 */
		System.out.println("please choose one to delete:");
		BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

		try
		{
			System.out.println("The client you delete is " + stdin.readLine());
			DeleteIP = AyServer.clients.get(Integer.parseInt(stdin.readLine()) - 1)
					.getIp();

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/**
		 * after input the choices we will disconnect the client you choose
		 */
	}

	/**
	 * exit the server
	 */
	protected void quit()
	{
		System.out.println("you have exited ");
		System.exit(0);
	}
}
